//
//  ObservableObject.m
//  WengWeng5
//
//  Created by HanFeng on 14-2-26.
//  Copyright (c) 2014年 mafengwo. All rights reserved.
//

#import "ObservableObject.h"

@interface ObservableObject () {
    NSPointerArray *_weakObservers;
}

@end

@implementation ObservableObject

- (NSArray *)observers
{
    @synchronized (self) {
        return [_weakObservers allObjects];
    }
}

- (id)init
{
    self = [super init];
    if (self) {
        _weakObservers = [NSPointerArray weakObjectsPointerArray];
    }
    return self;
}

- (void)registerObserver:(id)observer
{
    @synchronized (self) {
        [self _compactObservers];
        [_weakObservers addPointer:(__bridge void *)observer];
    }
}

- (void)unregisterObserver:(id)observer
{
    @synchronized (self) {
        for (int i = 0; i < _weakObservers.count; i++) {
            if ([_weakObservers pointerAtIndex:i] == (__bridge void *)observer) {
                [_weakObservers removePointerAtIndex:i];
                break;
            }
        }
        [self _compactObservers];
    }
}

- (void)_compactObservers
{
    @synchronized (self) {
        [_weakObservers compact];
        for (int i = 0; i < _weakObservers.count; i++) {
            if ([_weakObservers pointerAtIndex:i] == NULL) {
                [_weakObservers removePointerAtIndex:i];
                i--;
            }
        }
    }
}

@end
